import axios from 'axios'
import { ElLoading,ElMessage } from 'element-plus'
import store from "../store/index.js"

let loadingObj = null

const Service = axios.create({
    timeout: 5000, /* 数据响应过期时间 */
    baseURL: process.env.VUE_APP_BASE_API,
    headers:{
        "Content-Type":"application/json;charset=utf-8"
    }
})

/* 请求拦截器 增加loading */
Service.interceptors.request.use(config=>{
    loadingObj=ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    config.headers.Authorization = store.state.uInfo.userInfo.token
    return config
})
// 响应拦截-对返回值做统一处理
Service.interceptors.response.use(response=>{
    loadingObj.close()
    const data = response.data
    if(data.code!=200){
        ElMessage.error(data.msg||"服务器出错")
        // 请求出错
        return data 
    }
    return data

},error=>{
    loadingObj.close()
    ElMessage.error(error||"服务器出错")
    return Promise.reject(error);
})
// post请求
export const post=config=>{
    return Service({
        ...config,
        method:"post",
        data:config.data
    })
}
// get请求
export const get=config=>{
    return Service({
        ...config,
        method:"get",
        params:config.data
    })
}
// put请求
export const put=config=>{
    return Service({
        ...config,
        method:"put",
        data:config.data
    })
}// delete请求
export const del=config=>{
    return Service({
        ...config,
        method:"delete"
    })
}